import { Controller, Context, Post, Get, Delete, Use, sfn } from "nb2";
import { ResBody, Token } from "../common/model.js";
import { getToken } from "../common/utils.js";
import { prisma } from "../prisma.js";
import { handleAuth } from "../common/handleAuth.js";

@Controller("goods")
export class Goods {
  @Use(handleAuth)
  @Get("edit/:gid")
  async [sfn()](ctx: Context) {
    const gid = Number(ctx.params.gid);
    const goods = await prisma.goods.findUnique({
      where: { id: gid },
    });
    ctx.json<ResBody>({ code: 200, goods });
  }

  @Get("detail/:gid")
  async [sfn()](ctx: Context) {
    const gid = Number(ctx.params.gid);
    const token = await getToken(ctx);
    const goods = await prisma.goods.findUnique({
      where: { id: gid },
      include: { user: true, likes: true, collects: true },
    });

    const { likes, collects, ...rest } = goods!;
    const result = {
      ...rest,
      like_count: likes.length,
      liked_id: likes.find((c) => c.userId === token?.uid)?.id || null,
      //当前登录用户点赞id
      collected_id: collects.find((c) => c.userId === token?.uid)?.id || null,
      //当前登录用户收藏id
    };

    ctx.json<ResBody>({ code: 200, goods: result });
  }

  @Get("query-collect")
  async [sfn()](ctx: Context) {
    let page = ctx.query.page ? Number(ctx.query.page) : 1;
    let page_size = ctx.query.page_size ? Number(ctx.query.page_size) : 10;
    let uid = ctx.query.uid ? Number(ctx.query.uid) : undefined;

    const total = await prisma.collect.count({
      where: { userId: uid },
    });

    const collect = await prisma.collect.findMany({
      where: { userId: uid },
      take: page_size,
      skip: (page - 1) * page_size,
      orderBy: { createAt: "desc" },
      include: { goods: { include: { user: true, likes: true } } },
    });

    const token = await getToken(ctx);
    const result = collect.map(({ goods }) => ({
      ...goods,
      like_count: goods.likes.length,
      //当前登录用户点赞id
      liked_id: goods.likes.find((c) => c.userId === token?.uid)?.id || null,
    }));

    ctx.json<ResBody>({ code: 200, goods: result, total });
  }

  @Get("query")
  async [sfn()](ctx: Context) {
    let page = ctx.query.page ? Number(ctx.query.page) : 1;
    let page_size = ctx.query.page_size ? Number(ctx.query.page_size) : 10;
    const token = await getToken(ctx);
    const search = ctx.query.search;
    let uid = ctx.query.uid ? Number(ctx.query.uid) : undefined;

    const where = {
      userId: uid,
      OR: search
        ? [{ title: { contains: search } }, { intro: { contains: search } }]
        : undefined,
    };

    const total = await prisma.goods.count({
      where,
    });

    const goods = await prisma.goods.findMany({
      where,
      take: page_size,
      skip: (page - 1) * page_size,
      orderBy: { createAt: "desc" },
      include: {
        user: {
          select: {
            id: true,
            avatar: true,
            nickname: true,
          },
        },
        likes: true,
      },
    });

    let result = goods.map(({ likes, ...rest }) => ({
      ...rest,
      like_count: likes.length,
      //当前登录用户点赞id
      liked_id: likes.find((c) => c.userId === token?.uid)?.id || null,
    }));

    ctx.json<ResBody>({ code: 200, goods: result, total });
  }

  @Use(handleAuth)
  @Delete("delete/:gid")
  async [sfn()](ctx: Context) {
    const token = ctx.custom.token as Token;
    const gid = Number(ctx.params.gid);
    const goods = await prisma.goods.delete({
      where: {
        id: gid,
        userId: token.uid,
        //验证当前登录用户，是否是该商品的发布者
      },
    });

    ctx.json<ResBody>({ code: 200, msg: "删除成功", goods });
  }

  @Use(handleAuth)
  @Post("create")
  async [sfn()](ctx: Context) {
    const token = ctx.custom.token as Token;
    const body = await ctx.body("json");

    const goods = await prisma.goods.create({
      data: {
        status: body.status,
        files: body.files,
        preview: body.preview,
        tags: body.tags,
        title: body.title,
        intro: body.intro,
        plan: body.plan,
        price: body.price,
        userId: token.uid,
      },
    });
    ctx.json<ResBody>({ code: 200, msg: "创建成功", goods });
  }

  @Use(handleAuth)
  @Post("update/:gid")
  async [sfn()](ctx: Context) {
    const token = ctx.custom.token as Token;
    const body = await ctx.body("json");
    const gid = Number(ctx.params.gid);

    const saved = await prisma.goods.update({
      where: {
        id: gid,
        userId: token.uid, //是当前用户才能更新
      },
      data: {
        status: body.status,
        files: body.files,
        preview: body.preview,
        tags: body.tags,
        title: body.title,
        intro: body.intro,
        plan: body.plan,
        price: body.price,
      },
    });
    ctx.json<ResBody>({ code: 200, msg: "更新成功", goods: saved });
  }
}
